package com.guli.gulimall.gulimallproduct.exception;


import com.guli.common.utils.CodeEnume;
import com.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//@ControllerAdvice(basePackages = "com.guli.gulimall.gulimallproduct.controller")
@Slf4j
@RestControllerAdvice(basePackages = "com.guli.gulimall.gulimallproduct.controller")
public class GulimallExceptionCtroller {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handVailaException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
         log.error("数据校验出现问题{},异常类型:{},异常原因:{}",e.getMessage(),e.getClass(),e.getCause());
        Map<String,String> errorMap = new HashMap<>();
         result.getFieldErrors().forEach(fieldError -> {
             errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
         });
         return R.error(CodeEnume.VALID_EXCEPTION.getCode(),CodeEnume.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handException(Throwable e){

        return R.error(CodeEnume.UNKOW_EXCEPTION.getCode(),CodeEnume.UNKOW_EXCEPTION.getMsg());
    }


}
